package com.choryan.quan.videowzproject.extension

import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.Shader
import android.view.TouchDelegate
import android.view.View
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.widget.TextView
import com.shawn.baseappbygroovydsl.utils.ExtensionCommon.dp2px

/**
 * @author Secret
 * @since 2023/5/12
 */
object ExtensionView {

    fun View.show(){
        visibility = View.VISIBLE
    }

    fun View.hide(){
        visibility = View.GONE
    }

    fun View.hideIn() {
        visibility = View.INVISIBLE
    }

    /**
     * 扩展方法，扩大点击区域
     * NOTE: 需要保证目标targetView有父View，否则无法扩大点击区域
     *
     * @param expandSize 扩大的大小，单位px
     */
    fun View.expandTouchView(expandSize: Int = 10f.dp2px()) {
        val parentView = (parent as? View)
        parentView?.post {
            val rect = Rect()
            getHitRect(rect) //getHitRect(rect)将视图在父容器中所占据的区域存储到rect中。
            rect.left -= expandSize
            rect.top -= expandSize
            rect.right += expandSize
            rect.bottom += expandSize
            parentView.touchDelegate = TouchDelegate(rect, this)
        }
    }

    fun View.animationBreath() {
        val animation = ScaleAnimation(
            1f,
            1.05f,
            1f,
            1.05f,
            Animation.RELATIVE_TO_SELF,
            0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f
        )
        animation.duration = 300
        animation.repeatCount = Int.MAX_VALUE
        animation.repeatMode = Animation.REVERSE
        startAnimation(animation)
    }

    /**
     * 统一文字渐变色设置
     * @param colors 渐变色字符串数组
     * @param positions 渐变色位置数组，可为空
     * @param start 渐变起始点，可为空
     * @param end 渐变结束点，可为空
     * @param tile 渐变模式，默认为CLAMP
     */
    fun TextView.setGradientColor(
        colors: Array<String>,
        positions: FloatArray? = null,
        start: PointF? = null,
        end: PointF? = null,
        tile: Shader.TileMode = Shader.TileMode.CLAMP
    ) {
        addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
            val intColors = colors.map {
                Color.parseColor(it)
            }.toIntArray()
            val gradient = LinearGradient(
                start?.x ?: 0F,
                start?.y ?: 0F,
                end?.x ?: (right - left).toFloat(),
                end?.y ?: (bottom - top).toFloat(),
                intColors,
                positions,
                tile
            )
            paint.shader = gradient
            postInvalidate()
        }
    }
}